import axios, { type AxiosRequestHeaders, type AxiosResponse } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
const BASEURL = window.location.origin
class HttpService {
  static getAxiosInstance(
    url: string,
    timeout = 200000,
    headers: AxiosRequestHeaders,
  ) {
    // axios.defaults.withCredentials = true;
    const instance = axios.create({
      baseURL: url,
      timeout,
      headers,
    })
    instance.interceptors.request.use(this.onRequest, this.onError)
    instance.interceptors.response.use(this.onResponse, this.onError)
    return instance
  }

  static getAxios() {
    // axios.defaults.withCredentials = true;
    const instance = axios.create({
      timeout: 200000,
      headers: {
        'Content-Type': 'application/json;charset=utf8',
        reqEntrance: 'PC',
        // "Access-Control-Allow-Origin": "*",
        // "Access-Control-Allow-Credentials": true,
        // "Access-Control-Allow-Headers": "Content-Type",
      },
    })
    instance.interceptors.request.use(this.onRequest, this.onError)
    instance.interceptors.response.use(this.onResponse, this.onError)
    return instance
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private static onRequest(config?: any) {
    const userInfoStr = localStorage.getItem('userInfox')
    const userInfo = userInfoStr
      ? JSON.parse(localStorage.getItem('userInfox') as string).userInfo
      : {}
    config.headers!.ticket = userInfo.ticket || 'MTczOTQ5ODkyNzA2NklvaDJTaQ=='
    config.headers!.Authorization = 'xhsso-ticket ' + userInfo.ticket
    //打包到线上环境使用的地址
    if (
      import.meta.env.VITE_ENV === 'production' ||
      import.meta.env.VITE_ENV === 'test'
    ) {
      const url = new URL(config.baseURL as string)
      config.baseURL = BASEURL + url.pathname
    }
    return config
  }

  private static onResponse(response: AxiosResponse) {
    //返回body体无code，目前用于请求文件地址，获取文件流响应的处理
    response.data.code = response.data.code || 200
    //导出文件特殊处理
    if (!response.data.type) {
      if (response.data.code === 401) {
      }
      if (response.data?.result < 0) {
        ElMessage({
          message: response.data.message || '服务器异常，请稍后再试',
          grouping: true,
          type: 'error',
        })
        return response
      }
      if (response.data?.result >= 0) {
        return response
      }
      if (response.data.code == 10500) {
        ElMessageBox.close()
        ElMessageBox.alert(response.data.msg, '提示', {
          confirmButtonText: '知道了',
        })
        return Promise.reject(response)
      } else if (response.data.code !== 200) {
        ElMessage({
          message: response.data.msg || '服务器异常，请稍后再试',
          grouping: true,
          type: 'error',
        })
        return Promise.reject(response)
      }
    }
    return response
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private static onError(error: any) {
    ElMessage({
      message: '服务器异常，请稍后再试',
      grouping: true,
      type: 'error',
    })
    return Promise.reject(error.response)
  }
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const request = (url?: string, headers?: any) => {
  if (url) {
    return HttpService.getAxiosInstance(url, undefined, headers)
  } else {
    return HttpService.getAxios()
  }
}

export default request
